<template>
  <div class="top drag"></div>
  <BlankPage v-if="contactInfo === null"></BlankPage>
  <div v-else class="main" @click="switchNotesInformation(1)">
    <div class="main2">
      <div class="user">
        <div class="avatar-name">
          <div class="userimg">
            <el-avatar :size="60" :src="avatarName" shape="square" />
          </div>
          <div class="user-info">
            <div class="nick-name">
              <span>{{
                determineNoteNameIsEmpty(contactInfo.noteName)
                  ? contactInfo.nickName
                  : contactInfo.noteName
              }}</span>
              <span
                :class="['iconfont sex', contactInfo.sex === 1 ? 'icon-man' : 'icon-woman']"
              ></span>
            </div>
            <div
              v-if="!determineNoteNameIsEmpty(contactInfo.noteName)"
              class="info"
              style="overflow: hidden; text-overflow: ellipsis"
            >
              昵称：{{ contactInfo.nickName }}
            </div>
            <div class="info">甜蜜账号：{{ contactInfo.contactUserSweetCircleId }}</div>
            <div class="info">地区：{{ contactInfo.areaName }}</div>
          </div>
        </div>
        <div
          class="more2"
          title="更多"
          @click.stop="
            (e) => {
              more(e)
            }
          "
        >
          <span class="iconfont icon-more"></span>
        </div>
        <div v-if="showMoreCard" class="more2-card" :style="[{ left: x + 'px', top: y + 'px' }]">
          <el-card class="card">
            <div class="card-text" @click.stop="showSettingCard(1)">设置备注</div>
            <div class="card-text" @click.stop="showSettingCard(2)">设置甜甜圈权限</div>
            <div class="card-text" @click.stop="">把他推荐给好友</div>
            <div class="card-text" @click.stop="joinInBlacklist">加入黑名单</div>
            <div class="card-text" @click.stop="deleteContactPerson">删除联系人</div>
          </el-card>
        </div>
      </div>
      <div class="note note2">
        <div class="a">
          <div class="b">
            备注&nbsp; <span v-if="!isUpdateNoteName" class="c">{{ contactInfo.noteName }}</span>
          </div>
          <div class="c">
            <el-input
              v-if="isUpdateNoteName"
              v-model="noteName"
              placeholder="请填写备注信息"
              @click.stop
              @input="VerifyCharacterLength"
            >
              <template #suffix>
                <el-button key="primary" type="text" @click.stop="updateNoteName">保存</el-button>
              </template>
            </el-input>
          </div>
        </div>
        <div>
          <span
            v-if="!isUpdateNoteName"
            class="iconfont icon-bianji"
            style="cursor: pointer"
            @click.stop="switchNotesInformation(2)"
          ></span>
        </div>
      </div>
      <div class="note">
        <div>
          <span class="b">个性签名</span><span class="c">{{ contactInfo.personalSignature }}</span>
        </div>
      </div>
      <div class="ff">
        <div class="dd" @click="sendMessage">
          <span class="iconfont icon-message"></span>
          <span>发消息</span>
        </div>
        <div class="dd">
          <span class="iconfont icon-phone"></span>
          <span>语音聊天</span>
        </div>
        <div class="dd">
          <span class="iconfont icon-shexiangtou"></span>
          <span>视频聊天</span>
        </div>
      </div>
    </div>
  </div>
  <div v-if="showCardInfo" class="setting-card" @click.self="Tool.playWarningTone()">
    <el-card class="card-info">
      <div v-if="cardCode === 1" class="note">
        <div>
          <el-input v-model="noteName" placeholder="设置备注信息" @input="VerifyCharacterLength" />
        </div>
      </div>
      <!--        <div>-->
      <!--          <div>标签</div>-->
      <!--          <div><el-input v-model="addFriendApplyFormData.applyMsg"/></div>-->
      <!--        </div>-->
      <div v-if="cardCode === 2">
        <div class="sweet-circle-authority">
          <div class="b">
            <div class="c" style="cursor: pointer" @click.stop="cardForm.sweetCircleAuth = 1">
              <span style="color: #000000; font-size: 14px">聊天、甜甜圈</span
              ><span v-if="cardForm.sweetCircleAuth === 1" class="iconfont icon-dui active"></span>
            </div>
            <el-divider />
            <div class="c" style="cursor: pointer" @click.stop="cardForm.sweetCircleAuth = 2">
              <span style="color: #000000; font-size: 14px">仅聊天</span
              ><span v-if="cardForm.sweetCircleAuth === 2" class="iconfont icon-dui active"></span>
            </div>
          </div>
        </div>
        <div v-if="cardForm.sweetCircleAuth === 1" class="sweet-circle-authority">
          <div class="b">
            <div class="c">
              <span style="color: #000000; font-size: 14px">不让他（她）看</span>
              <el-switch
                v-model="cardForm.sweetCircleStatusA"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <el-divider />
            <div class="c">
              <span style="color: #000000; font-size: 14px">不看他</span>
              <el-switch
                v-model="cardForm.sweetCircleStatusB"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="button">
        <el-button class="confirm" type="primary" @click.stop="submit">确定</el-button>
        <el-button class="cancel" type="primary" @click.stop="showSettingCard(0)">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { computed, ref, watch } from 'vue'
import Tool from '#/utils/Tool'
import Api from '../../utils/Api'
import { useContactInfoStore } from '#/stores/ContactInfoStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import { ElMessage } from 'element-plus'
import BlankPage from './BlankPage.vue'
// import { useChatSessionStore } from '#/stores/ChatSessionStore'
const userInfoStore = useUserInfoStore()
const contactInfoStore = useContactInfoStore() // 存储联系人信息
// const chatSessionStore = useChatSessionStore()
const router = useRouter()

const showMoreCard = ref(false)
// 计算属性  返回路由参数的值
const contactInfo = computed(() => {
  return contactInfoStore.getContactInfo()
})

const avatarName = computed(() => {
  return Tool.getAvatar(contactInfo.value.contactUserId, contactInfo.value.avatar, 500)
})
const userInfo = computed(() => userInfoStore.getUserInfo())

const noteName = ref('')
const isUpdateNoteName = ref(false)

const x = ref(0)
const y = ref(0)

const showCardInfo = ref(false)
const cardForm = ref({
  userId: userInfo.value.userId,
  contactUserId: contactInfo.value.contactUserId,
  sweetCircleAuth: contactInfo.value.sweetCircleAuth,
  sweetCircleStatusA: contactInfo.value.sweetCircleStatusA,
  sweetCircleStatusB: contactInfo.value.sweetCircleStatusB
})
const cardCode = ref(0)

// 聊天列表
// const chatSessionInfoList = computed(() => {
//   return chatSessionStore.getChatSessionInfoList()
// })

const determineNoteNameIsEmpty = (notName) => {
  if (notName === '' || notName === null || notName === undefined) {
    return true
  }
}

const switchNotesInformation = async (num) => {
  showMoreCard.value = false
  if (num === 1) {
    isUpdateNoteName.value = false
  } else if (num === 2) {
    isUpdateNoteName.value = true
    noteName.value = contactInfo.value.noteName
  }
}

const updateNoteName = async () => {
  if (noteName.value.length > 15) {
    ElMessage.error('备注信息长度不能超过15个字符')
    noteName.value = ''
    return
  }
  // 更新备注信息  更新联系人的备注信息  再重新获取联系人列表
  const params = {
    userId: userInfo.value.userId,
    contactUserId: contactInfo.value.contactUserId,
    noteName: noteName.value
  }
  const res = await Api.updateContactNoteName(params)
  if (res.code === 200) {
    contactInfoStore.setContactInfoList(res.data)
    let contactInfo = contactInfoStore.getContactInfo()
    for (let i = 0; i < res.data.length; i++) {
      let bool = false
      let val = res.data[i]
      for (let j = 0; j < val.value.length; j++) {
        if (val.value[j].contactUserId === contactInfo.contactUserId) {
          contactInfoStore.setContactInfo(val.value[j])
          bool = true
          break
        }
      }
      if (bool) {
        break
      }
    }
  } else {
    ElMessage.error(res.msg)
  }
  isUpdateNoteName.value = false
}
const vh = ref(window.innerHeight) // 获取窗口高度
// const vh = ref(document.documentElement.clientHeight);
const vw = ref(window.innerWidth) // 获取窗口宽度
// 监听窗口变化
window.addEventListener('resize', () => {
  vh.value = window.innerHeight // 获取窗口高度
  vw.value = window.innerWidth // 获取窗口宽度
})

const more = (e) => {
  showMoreCard.value = true
  x.value = e.clientX > vw.value - 120 - 5 ? e.clientX - 120 - 5 : e.clientX // 设置删除卡片的 x 坐标
  y.value = e.clientY + 5
}

const showSettingCard = (code) => {
  showMoreCard.value = false
  switch (code) {
    case 0:
      showCardInfo.value = false
      cardCode.value = 0
      break
    case 1:
      showCardInfo.value = true
      cardCode.value = 1
      break
    case 2:
      showCardInfo.value = true
      cardCode.value = 2
      break
  }
}
const updateContactPersonInfo = async () => {
  const res = await Api.updateContactInfo(cardForm.value)
  if (res.code === 200) {
    ElMessage.success('修改成功')
    contactInfoStore.setContactInfo(res.data)
  } else {
    ElMessage.error(res.msg)
  }
}

const joinInBlacklist = async () => {
  showMoreCard.value = false
  const res = await Api.joinInBlacklist(cardForm.value)
  if (res.code === 200) {
    ElMessage.success('修改成功')
    contactInfoStore.setContactInfoList(res.data) // 设置新的联系人存储信息
    let contactInfo = contactInfoStore.getContactInfo() // 获取当前选择的联系人单独信息
    for (let i = 0; i < res.data.length; i++) {
      let bool = false
      let val = res.data[i]
      for (let j = 0; j < val.value.length; j++) {
        if (val.value[j].contactUserId === contactInfo.contactUserId) {
          contactInfoStore.setContactInfo(val.value[j]) // 修改当前选择的联系人单独信息
          bool = true
          break
        }
      }
      if (bool) {
        break
      }
    }
    // 查找加入黑名单的联系人添加到本地存储
    let arr = []
    for (let i = 0; i < res.data.length; i++) {
      let val = res.data[i]
      for (let j = 0; j < val.value.length; j++) {
        if (val.value[j].friendsCode === 2) {
          arr.push(val.value[j])
        }
      }
    }
    contactInfoStore.setContactBlacklistList(arr)
  } else {
    ElMessage.error(res.msg)
  }
}

const deleteContactPerson = async () => {
  //user.contactUserId  删除的联系人用户id
  // 后端删除联系人
  const res = await Api.deleteContact({
    userId: userInfo.value.userId,
    contactUserId: contactInfo.value.contactUserId
  })
  if (res.code === 200) {
    let contactListNew = contactInfoStore.getContactInfoList()
    for (let i = 0; i < contactListNew.length; i++) {
      let item = contactListNew[i].value // 获取联系人数组
      let over = false
      for (let j = 0; j < item.length; j++) {
        // 遍历联系人数组
        let item2 = item[j] // 获取联系人数组的联系人对象
        if (item2.contactUserId === contactInfo.value.contactUserId) {
          item.splice(j, 1)
          over = true
          break
        }
      }
      if (over) {
        break
      }
    }
    contactInfoStore.setContactInfoList(contactListNew) //重新设置联系人列表

    //  删除会话 消息
    const res2 = await window.ipcRenderer.invoke(
      'deleteChatSession',
      contactInfo.value.contactUserId,
      true
    )
    if (!res2.status) {
      ElMessage.error(res2.msg)
    }
    let u = contactInfoStore.getContactInfo()
    // 如果删除的为当前选中联系人 就设置为 空取消选中状态
    if (u.contactUserId === contactInfo.value.contactUserId) {
      contactInfoStore.setContactInfo(null)
    }
    ElMessage.success('删除联系人成功')
    showMoreCard.value = false
    contactInfo.value = null
  }
}

const submit = () => {
  switch (cardCode.value) {
    case 1: // 更新备注
      updateNoteName()
      showSettingCard(0)
      break
    case 2: //更新甜甜圈权限
      updateContactPersonInfo()
      showSettingCard(0)
      break
  }
}

/**
 * 验证字符长度
 * @returns {boolean}
 * @constructor
 */
const VerifyCharacterLength = () => {
  if (noteName.value.length > 15) {
    noteName.value = noteName.value.substring(0, 15)
    ElMessage.error('备注信息长度不能超过15个字符')
    return false
  }
}

const sendMessage = () => {
  router.push({
    path: '/chat',
    query: { sessionId: contactInfo.value.contactUserId, timestamp: new Date().getTime() }
  })
}

watch(
  () => contactInfo.value,
  () => {
    showMoreCard.value = false
  }
)

// 监视 路由参数 动态更新数据
// watch(
//   () => route.query.contactInfo,
//   (newVal, oldVal) => {
//     if (newVal) {
//       contactInfo.value = JSON.parse(Tool.base64ToString(newVal))
//     }
//   },
//   { immediate: true, deep: true }
// );
</script>
<style lang="scss" scoped>
.top {
  height: 60px;
}

.main {
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  padding-top: 50px;
  height: calc(100vh - 60px);

  .main2 {
    width: 400px;
  }

  .user {
    padding-bottom: 20px;
    display: flex;
    border-bottom: 1px solid #b6b6b6;
    justify-content: space-between;

    .avatar-name {
      flex: 10;
      display: flex;
      justify-content: space-between;

      .user-info {
        margin-left: 10px;
        flex: 10;

        .nick-name {
          white-space: nowrap;
          color: #000000;

          .icon-man {
            color: #2cb6fe;
          }

          .icon-woman {
            color: #fb7373;
          }
        }

        .info {
          font-size: 13px;
          color: #9e9e9e;
          margin-top: 3px;
        }
      }
    }

    .more2 {
      width: 25px;
      height: 25px;
      border-radius: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;

      &:hover {
        background-color: #e0e0e0;
      }
    }
  }

  .note {
    margin-top: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #b6b6b6;

    .b {
      color: #8c8c8c;
      margin-right: 10px;
    }

    .bb {
      color: #8c8c8c;
      margin-right: 38px;
    }

    .c {
      color: #000000;
    }
  }
}

.note2 {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .a {
    flex: 1;
    display: flex;
    align-items: center;

    .c {
      flex: 1;
    }
  }
}

.dd {
  margin: 15px;
  width: 80px;
  height: 50px;
  align-items: center;
  display: flex;
  flex-direction: column;
  color: #566a95;

  .iconfont {
    font-size: 20px;
    margin: 5px;
  }

  span {
    font-size: 12px;
  }

  &:hover {
    background-color: #e0e0e0;
  }
}

.ff {
  display: flex;
  justify-content: center;
  user-select: none;
}

.more2-card {
  position: absolute;
  z-index: 1;

  .card {
    border-radius: 0;
    width: 120px;
    height: auto;
    display: flex;
    flex-direction: column;
    align-items: center;

    .card-text {
      width: 120px;
      user-select: none;
      font-size: 13px;
      height: 25px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border-bottom: 0.5px solid #eaeaea;

      &:hover {
        background: #eaeaea;
      }
    }
  }
}

.setting-card {
  user-select: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .card-info {
    width: 300px;
    height: auto;
    padding: 15px;

    .note {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      border: none;
    }

    .sweet-circle-authority {
      .b {
        background: #ffffff;
        padding: 15px;

        .c {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
        }
      }
    }

    .button {
      height: 50px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-button {
        width: 100px;
      }

      .cancel {
        background-color: #dfdfe0;
        border: none;
        color: #07c160;

        &:hover {
          background-color: #c0c0c0;
        }
      }
    }
  }
}

.el-divider {
  margin: 10px 0 10px 0;
}

.active {
  color: #07c160;
}

.el-switch {
  height: 100%;
}

:deep(.el-badge__content) {
  border: none;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>
